<template>
  <div class="app-container">
    <!-- 工具栏：标题和按钮在同一行 -->
    <div class="toolbar">
      <h1 class="toolbar-title">优质大豆补贴请示(乡级)</h1>

      <div class="button-group">
        <!-- 左侧按钮 -->
        <button type="button" class="btn-primary" @click="handleStamp()">电子印章</button>
        <button type="button" class="btn-primary" @click="submitTownRequest()">提交</button>
        <!-- <button type="button" class="btn-primary" @click="submitTownCheck()">上传扫描件</button> -->

        <!-- 右侧按钮组（自动推到右边） -->
        <div class="right-buttons">
          <button type="button" class="btn-primary" @click="handleExportPdf()">导出PDF</button>
          <button type="button" class="btn-primary" @click="handlePreview()">预览</button>
        </div>
      </div>
      <div style="width: 100%;height: 200px;">
        <el-form ref="elForm" :model="form" :rules="rules" size="medium" label-width="100px" label-position="left">
          <el-row>
            <el-col :span="12">
              <el-form-item label="红头标题" prop="redTitle">
                <el-input v-model="form.redTitle" placeholder="红头标题" clearable :style="{ width: '100%' }"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="文号" prop="redCode">
                <el-input v-model="form.redCode" placeholder="文号" clearable :style="{ width: '100%' }"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="12">
            <el-col :span="12">
              <el-form-item label="申请人类型" prop="personType">
                <el-select v-model="form.personType" placeholder="申请人类型" clearable :style="{ width: '100%' }">
                  <el-option v-for='item in personTypes' :label="item.label" :key="item.value"
                    :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申报单位" prop="enterprise">
                <el-input v-model="form.enterprise" placeholder="申报单位" clearable :style="{ width: '100%' }"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="优质大豆品种数" prop="dadouType" label-width="130px">
                <el-input v-model="form.dadouType" placeholder="优质大豆品种数" type="number" clearable
                  :style="{ width: '100%' }"></el-input>
              </el-form-item>
            </el-col>
            
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="下发文件" prop="dadouNotice" >
                <el-input v-model="form.dadouNotice" placeholder="请输入文件名" type="textarea"
                  :autosize="{ minRows: 1, maxRows: 4 }" clearable :style="{ width: '100%' }"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>

    <!-- PDF 内容区域 -->
    <div class="pdfDom" id="pdfDom">
      <!-- 红头部分 -->
      <div class="red-header">
        <h1 class="red-title">{{ form.redTitle }}</h1>
      </div>

      <!-- 文号 -->


      <!-- 红线与五角星 -->
      <!-- <el-divider><i class="el-icon-star-on"></i></el-divider> -->
      <div class="separator">
        <div class="red-line"></div>
        <div class="red-line1"></div>
      </div>
      <div class="doc-number">
        {{ form.redCode }}
      </div>

      <!-- 标题 -->
      <p class="title">关于申报{{ townName }}{{ year }}年优质大豆生产奖补政策的函</p>


      <!-- 主送机关：顶格 -->
      <p class="addressee">区农业农村局：</p>

      <!-- 正文：首行缩进 -->
      <p class="content">
        按照省农业农村厅、省财政厅联合下发的{{ form.dadouNotice }}文件要求，我{{ form.personType }}积极开展{{ year}}年优质大豆生产奖补政策宣传，让农民及时了解补贴政策内容。按照高油高产大豆补贴种植户和高蛋白大豆补贴种植户申报情况，依据{{ year }}年发放大豆生产者补贴的面积以及文件要求的{{ form.dadouType}}种优质大豆品种、发票、农业农村厅监制的种子销售凭证、购买公斤数、承租合同等佐证材料，经过逐级核实、申报、公示。现申报优质大豆生产补贴面积{{ sumData.youdoubyxitotal }}亩。其中高油高产大豆{{sumData.youdouGaoyoubyxitotal}}亩，高蛋白大豆{{ sumData.youdouGaodanbaibyxitotal }}亩。
      </p>


      <!-- 发文机关和日期 -->
      <div class="footer">
        <p>{{ form.enterprise }}</p>
        <p>{{ year }}年{{ month }}月{{ day }}日</p>
      </div>
    </div>
  </div>
</template>
  
<script>
import { listProduce, submitProduce, queryGroupData, queryTownRes } from "@/api/agriculture/agriculture";
import { stamp } from "@/api/agriculture/file";

export default {
  name: "TownRequest",
  data() {
    const now = new Date();
    return {
      straName: '滴道区',
      townName: '',
      userName: '',
      role: '',

      year: now.getFullYear(),
      month: String(now.getMonth() + 1),
      day: String(now.getDate()),
      htmlTitle: '优质大豆补贴请示',

      //进度条
      buttonLoading: false,
      uploadLoading: null, // 用于保存 loading 实例
      progressText: '正在准备盖章文件...',

      //控制是否下载
      isDownload: false, //否为不下载
      tableData: [],

      queryTownSubUrl: '',//查询到的自己提交资金请示文件
      filePdf: undefined,  //生成的PDF-file
      fileExcel: undefined,
      filePdfUrl: undefined,   //电子印章返回的url
      fileExcelUrl: undefined,

      sumData: {},


      queryParams: {
        straName: '滴道区',
        townName: undefined,
        appType: undefined,
        year: now.getFullYear(),
        pageNum:1,
        pageSize:10
      },

      form: {
        redTitle: '人民政府文件',
        redCode: '〔2025〕号',//机关代字
        dadouType: '343', //优质大豆品种
        dadouNotice: '《关于组织申报2025年优质大豆奖补资金的通知》（黑农厅联发函（2025）726号）', //下发的文件全称
        personType: '乡',//申请区域的类型，我乡，我农场，我区
        enterprise: '人民政府'
      },
      rules: {
        redCode: [{
          required: true,
          message: '请输入机关代字',
          trigger: 'blur'
        }],
        redTitle: [{
          required: true,
          message: '请输入红头文件名',
          trigger: 'blur'
        }],
        enterprise: [{
          required: true,
          message: '请输入申报单位',
          trigger: 'blur'
        }],
        dadouType: [{
          required: true,
          message: '请输入优质大豆品种总数',
          trigger: 'blur'
        }],
        dadouNotice: [{
          required: true,
          message: '请输入文件名',
          trigger: 'blur'
        }],
        personType: [{
          required: true,
          message: '请选择申请方类型',
          trigger: 'change'
        }]
      },
      personTypes: [{
        "label": "乡",
        "value": "乡"
      },
      {
        "label": "镇",
        "value": "镇"
      },
      {
        "label": "林场",
        "value": "林场"
      },
      {
        "label": "农场",
        "value": "农场"
      },
      {
        "label": "公司",
        "value": "公司"
      }]
    };
  },
  created() {
    console.log("目前登录的角色是", this.$store.state.user.user, this.$store.state.user.roles[0])
    console.log("路由参数", this.$route.query.checkType)
    this.queryParams.appType = this.$route.query.checkType
    this.role = this.$store.state.user.roles[0];

    this.townName = this.$store.state.user.user.townName;
    this.queryParams.townName = this.townName;

    this.htmlTitle = this.townName + '补贴请示';

    this.getList();
    this.getGroupList();

  },
  methods: {

    async handlePreview() {
      await queryTownRes({ year: this.year, type: this.queryParams.appType, name: this.townName, isprice: '1' }).then(res => {
        if (res.rows.length > 0 && res.rows[res.rows.length - 1].hechafile) {
          console.log("res", res.rows[res.rows.length - 1].hechafile)
          this.queryTownSubUrl = res.rows[res.rows.length - 1].hechafile.replace('172.24.254.135', '111.40.188.220');
          console.log("res2", this.queryTownSubUrl)
        }
      })

      if (this.queryTownSubUrl) {
        this.$modal.msgSuccess("打开已提交的请示文件");
        // this.$router.push({ name: 'PdfViewer', query: { url: this.queryTownSubUrl } })
        const routeData = this.$router.resolve({
          name: 'PdfViewer',
          query: { url: this.queryTownSubUrl }
        });
        window.open(routeData.href, '_blank');
      }
      else if (this.filePdfUrl) {
        this.$modal.msgSuccess("打开已盖章的请示文件");
        // this.$router.push({ name: 'PdfViewer', query: { url: this.getProxyUrl(this.filePdfUrl) } })
        const routeData = this.$router.resolve({
          name: 'PdfViewer',
          query: { url: this.getProxyUrl(this.filePdfUrl) }
        });
        window.open(routeData.href, '_blank');
      } else {
        this.$message({
          message: '还未进行盖章',
          type: 'warning'
        });
      }
    },
    //替换
    getProxyUrl(originalUrl) {
      return originalUrl.replace(/^(https?):\/\/172\.24\.254\.135/, '$1://111.40.188.220');
    },
    async handleStamp() {
      this.buttonLoading = true;

      // 显示全局 loading，带进度文字
      this.uploadLoading = this.$loading({
        lock: true,
        text: this.progressText,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });

      try {
        // --- 步骤1：生成 PDF ---
        this.progressText = '正在生成 PDF 文件...';
        this.uploadLoading.text = this.progressText;
        await this.handlePdf(false);
        if (!this.filePdf) {
          this.$modal.msgError("PDF 生成失败");
          return;
        }
        console.log("生成的pdf", this.filePdf)
        // --- 步骤2：上传并盖章（耗时操作）---
        this.progressText = '正在上传并盖章，请耐心等待...';
        this.uploadLoading.text = this.progressText;

        const formData = new FormData();
        formData.append("file", this.filePdf);
        formData.append("signArea", '1');

        const res = await stamp(formData); // 假设这个接口很慢

        // --- 成功 ---
        this.filePdfUrl = res.msg;

        console.log("盖章的pdf", this.filePdfUrl);
        this.$modal.msgSuccess("盖章成功");

      } catch (error) {
        console.error("盖章失败", error);
        this.$modal.msgError("操作失败：" + (error.message || "未知错误"));
      } finally {
        // 关闭 loading
        if (this.uploadLoading) {
          this.uploadLoading.close();
        }
        this.uploadLoading = null;
        this.buttonLoading = false;
        this.progressText = '正在准备盖章文件...'; // 重置
      }
    },

    async handleExportPdf() {
      try {
        await this.handlePdf(true);
      } catch (error) {
        console.error("导出PDF失败", error);
        this.$modal.msgError("操作失败：" + (error.message || "未知错误"));
      }

    },
    //生成pdf和blob，并控制是否下载
    async handlePdf(value) {
      return new Promise(async (resolve, reject) => {
          // 使用 validate 的回调，但包裹在 Promise 中
          this.$refs['elForm'].validate(async (valid) => {
            if (valid) {
              await this.$nextTick(); // 确保 DOM 更新
              try {
                const pdfBlob = await this.getPdf({ download: value }); // 这里 await getPdf()
                console.log("pdfBlob", pdfBlob);

                this.filePdf = new File([pdfBlob], '乡级资金请示.pdf', {
                  type: 'pdf',
                  lastModified: Date.now()
                });
                resolve(); // ✅ 成功生成文件，resolve
              } catch (error) {
                console.error("生成 PDF 失败", error);
                reject(error);
              }
            } else {
              reject(new Error("表单验证未通过"));
            }
          });
        
      });
    },



    getGroupList() {
      this.tableLoading = true;
      const queryTab = { year: this.year, appType:this.queryParams.appType, townName: this.townName };
      console.log("queryTab", queryTab)
      queryGroupData(queryTab).then(response => {
        console.log("分村数据", response);
      })
    },
    getList() {
      this.tableLoading = true;
      console.log("查询表单", this.queryParams);
      listProduce(this.queryParams).then(response => {

        this.total = response.total; // 总条数
        this.sumData = response;
      })
    },

    submitTownRequest() {
      //乡级一键提交
      if (this.filePdfUrl) {
        submitProduce({ hechafile: this.filePdfUrl, year: this.year, appType: this.queryParams.appType, name: this.townName, isprice: "1" }).then(response => {
          console.log("res", response)
          this.$modal.msgSuccess("提交成功");

        }).catch(error => {
          this.$message({ type: 'error', message: '请重新电子盖章并等待!' });
        });
      } else {
        this.$message({ type: 'error', message: '还没有对文件进行电子盖章!' });
      }

    }
  }

};
</script>
  
<style scoped>
.app-container {
  width: 60%;
  align-items: center;
  margin-left: 20%;
  padding: 20px;
  font-family: "SimSun", "宋体", serif;
  color: black;
}

.pdfDom {
  width: 210mm;
  min-height: 297mm;
  margin: 0 auto;
  padding: 30mm 30mm;
  box-sizing: border-box;
  background-color: white !important;
  position: relative; /* 必须加 */
  /* 必须加 !important */
  /* box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); */
}

/* 红头标题 */
.red-header .red-title {
  font-size: 54px;
  /* 约72px视觉效果，但更标准 */
  text-align: center;
  color: red;
  font-weight: 700;
  margin-bottom: 80px;
  letter-spacing: 0.5px;
  font-family: "SimSun", "宋体";
}

/* 文号 */
.doc-number {
  text-align: right;
  font-size: 20px;
  font-weight: 400;
  /* margin: 10px 0; */
  font-family: "SimSun", "宋体";
}

/* 分隔线 + 五角星 */
.separator {
  /* display: flex; */
  align-items: center;
  justify-content: center;
  /* margin: 20px 0; */
}

.red-line {
  width: 100%;
  height: 4px;
  background-color: rgb(238, 0, 0);
  /* margin: 0 10px; */
}

.red-line1 {
  width: 100%;
  height: 2px;
  background-color: rgb(238, 0, 0);
  margin-top: 2px;
  /* margin: 0 10px; */
}


.star {
  color: rgb(238, 0, 0);
  font-size: 28px;
  font-weight: bold;
}

/* 标题 */
.title {
  text-align: center;
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 20px;
  width: 94%;
  margin-left: 3%;
  line-height: 1.8;
  font-family: "SimSun", "宋体";
  color: #000;
  /* 显式设置黑色 */
}

/* 主送机关：顶格左对齐 */
.addressee {
  text-align: left;
  font-size: 20px;
  line-height: 1.6;
  font-weight: 400;
  text-indent: 0;
  margin: 0;
}

/* 正文段落：首行缩进2字符 */
.content {
  text-indent: 2em;
  font-size: 20px;
  line-height: 1.6;
  /* font-weight: bold; */
  text-align: justify;
  font-weight: 400;
  font-family: "SimSun", "宋体";
}

/* 落款（发文机关 + 日期） */
.footer {
  position: absolute;
  bottom: 12%;
  right: 30mm;
  text-align: right;
  font-size: 20px;
  font-weight: 400;
  font-family: "SimSun", "宋体";
}

/* 工具栏：标题和按钮水平排列 */
.toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 20px;
  /* 按钮之间、标题与按钮之间的间距 */
  margin-bottom: 20px;
  flex-wrap: wrap;
  /* 小屏幕时换行 */
}

.toolbar .toolbar-title {
  margin: 0;
  font-size: 24px;
  color: #333;
  font-weight: bold;
  white-space: nowrap;
}

.button-group {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  /* 左对齐整体内容 */
  gap: 30px;
  width: 100%;
  padding: 10px 0;
}

/* 关键：使用 margin-left: auto 将右侧推到最右边 */
.right-buttons {
  margin-left: auto;
  /* 👈 核心：自动占据左侧空白 */
  display: flex;
  gap: 30px;
}

.btn-primary {
  padding: 8px 16px;
  font-size: 14px;
  border: none;
  border-radius: 4px;
  background-color: #007bff;
  color: white;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-primary:hover {
  background-color: #0056b3;
}

/* 响应式：小屏幕下工具栏换行 */
@media (max-width: 600px) {
  .toolbar {
    flex-direction: row;
    align-items: flex-start;
  }

  /* .button-group {
    margin-top: 8px;
    margin-right: 8px;

  } */
}
</style>